/**
 * Copyright (c)  HeiFeiDeFengZheng.Co.Ltd. All rights reserved.
 **/
package com.defu.newmall.config;

import com.defu.newmall.annotation.TokenToUser;
import com.defu.newmall.common.Constants;
import com.defu.newmall.common.ResultGenerator;
import com.defu.newmall.dao.NewBeeAdminUserTokenDao;
import com.defu.newmall.entity.AdminUserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 功能描述：
 *
 * @author huifeidefengzheng
 * @since 2024-01-28
 *
 **/
@Component
public class TokenToAdminUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private NewBeeAdminUserTokenDao newBeeAdminUserTokenDao;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        if (parameter.hasParameterAnnotation(TokenToUser.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        if (parameter.getParameterAnnotation(TokenToUser.class) instanceof TokenToUser) {
            String token = webRequest.getHeader("NewbeeToken");
            if (null != token && !"".equals(token) && token.length() == Constants.TOKEN_LENGTH) {
                AdminUserToken adminUserToken = newBeeAdminUserTokenDao.selectByToken(token);
                if (adminUserToken == null) {
                    return ResultGenerator.genFailResult("未登录");
                } else if (adminUserToken.getExpireTime().getTime() <= System.currentTimeMillis()) {
                    return ResultGenerator.genFailResult("登录超时");
                }
                return adminUserToken;
            } else {
                return ResultGenerator.genFailResult("登录失败");
            }
        }
        return null;
    }
}
